const Router = require('koa-router');
const tool = require("../../tools/tool");
const router = new Router();
const {db, Op, QueryTypes} = require("../../models/db");
// 商品历史价格
router.post('/bill/priceHist', async ctx => {
    let user = ctx.user
    let body = ctx.request.body
    let tenantId = user.tenantId;
    let invId = body.invId;
    let buId = tool.xe.toNumber(body.buId);
    let transType = tool.xe.toNumber(body.transType);
    if(!invId) return ctx.err('还没选择商品')
    if(!transType) return ctx.err('还没选择业务类型')
    let jsonObject = {
        qty: 0,
    };
    try {
        let good = await db.models['vGoods'].findOne({
            where: {
                tenantId,
                id: invId
            },
            attributes: ['id', 'spec', 'unit1', 'unit2', 'price1', 'price2']
        })
        if(!good) {
            return  ctx.err('该商品未找到')
        }

        let unit = good.unit1

        let sql = `SELECT tenantId,buId,transType,invId,unit,price,deduction from v_price_his_last 
        where tenantId=${tenantId} and transType=${transType} and buId=${buId} and invId=${invId} 
          and unit='${unit}' and price > 0 order by id desc`;
        let priceHis = await db.query(sql, { type: QueryTypes.SELECT, plain: true })
        if (!priceHis) {
            jsonObject.unit = good.unit1
            jsonObject.unit1 = good.unit1
            jsonObject.unit2 = good.unit2
            jsonObject.spec = good.spec
            jsonObject.location = []
            jsonObject.unitList = [
                {id: good.unit1, name: good.unit1},
            ]
            if(good.unit2) {
                jsonObject.unitList.push( {id: good.unit2, name: good.unit2})
            }
            return ctx.suc('', jsonObject);
        }
        priceHis.unit1 = good.unit1
        priceHis.unit2 = good.unit2
        priceHis.unitList = [
            {id: good.unit1, name: good.unit1},
        ]
        if(good.unit2) {
            priceHis.unitList.push( {id: good.unit2, name: good.unit2})
        }
        priceHis.spec = good.spec
        priceHis.location = []

        return ctx.suc('', priceHis);
    } catch (e) {
        return ctx.err(e);
    }

})

module.exports = router;